const router = require('koa-router')()
const mongoose =require('mongoose')

const Image = mongoose.model('Image')
const stats = require('../helper/stats')
const Comment = mongoose.model('Comment')

router.get('/', async (ctx, next) => {
  await Promise.all([
      Image.find().sort({timestamp: -1}),
      Comment.find().sort({timestamp: -1}).limit(9).populate('image'),
      Image.find().sort({like:-1}).limit(9),
      stats()
  ])
  .then(([images,comments,popular,stats])=> ctx.render('index',
    {images,comments,popular,stats}
    ))
  .catch(err =>ctx.throw(500,err))
  })

module.exports = router
